import { login, refreshToken } from '@/views/tmpt/auth/api/user.js'
import { getToken, setToken, removeToken, setRefreshToken, getRefreshToken, removeRefreshToken, getAuths, setAuths, removeAuths, getUser, setUser, removeUser } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import store from "@/store";
import Cookies from 'js-cookie'
import storageUtil from '@/utils/StorageUtil'
import {load} from "runjs/lib/script";

const state = {
  token: getToken(),
  avatar: '',
  introduction: '',
  roles: getAuths(),
  user: getUser(),
  isLoadedMenus: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, auths) => {
    state.roles = auths
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  LoadedMenus: (state, status) => {
    state.isLoadedMenus = status
  }
}


// scope: "all PRODUCT_API"
// user: "{"createTime":"2016-10-19T02:31:18.000+0000","loginName":"admin123","name":"jackson","state":true,"userId":1}"
const grant_type = 'password'
const actions = {

    // user login
    async login ({commit}, userInfo) {
        const { username, password } = userInfo
        let result = await login({ username: username.trim(), password: password, grant_type: grant_type })
        if (!result.success) {
            return result
        }

        const { access_token, refresh_token, authorities, user } = result.map
        // set a default avatar
        const userJson = user //JSON.parse(user)
        userJson.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
        commit('SET_TOKEN', access_token)
        commit('SET_ROLES', authorities)
        commit('SET_AVATAR', '')
        commit('SET_INTRODUCTION', 'my introduction')
        commit('SET_USER', userJson)

        setToken(access_token)
        setAuths(authorities)
        setUser(userJson)
        setRefreshToken(refresh_token)

        // 加载用户页面配置信息
        let resultUS = await storageUtil.loadByUserId(user.userId)
        return resultUS

    },

    // refresh token
    refreshToken({ commit }, result) {
        if (result.success) {
            // const { access_token, authorities, token_type, refresh_token, expires_in, scope, user, jti } = data
            const { access_token, refresh_token, authorities, user } = result.map
            // set a default avatar
            const userJson = user //JSON.parse(user)
            userJson.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
            commit('SET_TOKEN', access_token)
            commit('SET_ROLES', authorities)
            commit('SET_AVATAR', '')
            commit('SET_INTRODUCTION', 'my introduction')
            commit('SET_USER', userJson)

            setToken(access_token)
            setAuths(authorities)
            setUser(userJson)
            setRefreshToken(refresh_token)
        }
    },


    // remove token
    resetToken({ commit, state, dispatch }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_USER', {})
            removeToken()
            removeAuths()
            removeUser()
            resetRouter()
            commit('LoadedMenus', false)
            dispatch('tagsView/delAllViews', null, { root: true })
            resolve()
        })
    },

    /*// refresh token
    refreshToken({ commit }) {
        return new Promise((resolve, reject) => {
            let data = {}
            data.grant_type = 'refresh_token'
            data.refresh_token = Cookies.get('refresh_token')
            refreshToken(data).then(result => {
                //console.log(result)
                if (result.success) {
                    // const { access_token, authorities, token_type, refresh_token, expires_in, scope, user, jti } = data
                    const { access_token, refresh_token, authorities, user } = result.map
                    // set a default avatar
                    const userJson = JSON.parse(user)
                    userJson.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
                    commit('SET_TOKEN', access_token)
                    commit('SET_ROLES', authorities)
                    commit('SET_AVATAR', '')
                    commit('SET_INTRODUCTION', 'my introduction')
                    commit('SET_USER', userJson)

                    setToken(access_token)
                    setAuths(authorities)
                    setUser(userJson)
                    Cookies.set('refresh_token',refresh_token)

                    resolve()
                }
            }).catch(error => {
              //console.log(error)
              reject(error)
            })
        })
    },*/

    loadedMenus({ commit }) {
      commit('LoadedMenus', true)
    },

    // get user info
    /* getInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const { data } = response

          if (!data) {
            reject('Verification failed, please Login again.')
          }

          const { roles, name, avatar, introduction } = data

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!')
          }

          commit('SET_ROLES', roles)
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },*/

    // user logout
    logout({ commit, state, dispatch }) {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USER', {})
      removeToken()
      removeRefreshToken()
      removeAuths()
      removeUser()
      resetRouter()
      commit('LoadedMenus', false)
      dispatch('tagsView/delAllViews', null, { root: true })

      /* return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_USER', {})
          removeToken()
          removeAuths()
          removeUser()
          resetRouter()

          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch('tagsView/delAllViews', null, { root: true })

          resolve()
        }).catch(error => {
          reject(error)
        })
      })*/
    },


    // dynamically modify permissions
    changeRoles({ commit, dispatch }, role) {
      return new Promise(async resolve => {
        const token = role + '-token'

        commit('SET_TOKEN', token)
        setToken(token)

        const { roles } = await dispatch('getInfo')

        resetRouter()

        // generate accessible routes map based on roles
        const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

        // dynamically add accessible routes
        router.addRoutes(accessRoutes)

        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      })
    }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
